package com.bigdata.service.controller.app;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.date.DateUtil;
import com.bigdata.common.annotation.Log;
import com.bigdata.common.annotation.RepeatSubmit;
import com.bigdata.common.core.controller.BaseController;
import com.bigdata.common.core.domain.PageQuery;
import com.bigdata.common.core.domain.R;
import com.bigdata.common.core.page.TableDataInfo;
import com.bigdata.common.core.validate.AddGroup;
import com.bigdata.common.core.validate.EditGroup;
import com.bigdata.common.enums.BusinessType;
import com.bigdata.common.helper.LoginHelper;
import com.bigdata.common.utils.StringUtils;
import com.bigdata.service.domain.bo.DatasetsBo;
import com.bigdata.service.domain.bo.HotSearchBo;
import com.bigdata.service.domain.bo.PointTransactionsBo;
import com.bigdata.service.domain.bo.UserPointsBo;
import com.bigdata.service.domain.vo.*;
import com.bigdata.service.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据集主
 *
 * @author ruoyi
 * @date 2025-07-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/service/datasets")
public class AppDatasetsController extends BaseController {

    private final IDatasetsService iDatasetsService;

    private final IHotSearchService iHotSearchService;

    private final IServiceUsersService serviceUsersService;

    private final IUserPointsService userPointsService;

    private final IPointTransactionsService pointTransactionsService;



    /**
     * 查询数据集主列表
     */
    @SaIgnore
    @PostMapping("/list")
    public TableDataInfo<DatasetsVo> list(@RequestBody DatasetsBo bo) {

        if(StringUtils.isNotBlank(bo.getTitle())){
            HotSearchBo searchBo =  new HotSearchBo();
            searchBo.setKeyword(bo.getTitle());
            List<HotSearchVo> list = iHotSearchService.queryList(searchBo);
            if(list != null && list.size() > 0){
                searchBo =  new HotSearchBo();
                searchBo.setId(list.get(0).getId());
                searchBo.setSearchCount(String.valueOf(Integer.parseInt(list.get(0).getSearchCount()) + 1));
                iHotSearchService.updateByBo(searchBo);
            }else {
                HotSearchBo addBo =  new HotSearchBo();
                addBo.setKeyword(bo.getTitle());
                addBo.setSearchCount("1");
                iHotSearchService.insertByBo(addBo);
            }
        }
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        bo.setDatasetStatus(2);
        bo.setListingStatus(1);
        pageQuery.setOrderByColumn(bo.getOrderByColumn());
        return iDatasetsService.queryPageList(bo, pageQuery);
    }


    /**
     * 查询数据集主列表
     */
    @SaIgnore
    @PostMapping("/newList")
    public TableDataInfo<DatasetsVo> newList(@RequestBody DatasetsBo bo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        bo.setStartTime(DateUtil.offsetDay(new Date(), -25));
        bo.setEndTime(DateUtil.date());
        bo.setDatasetStatus(2);
        bo.setListingStatus(1);
        return iDatasetsService.queryPageList(bo, pageQuery);
    }


    /**
     * 根据访问量查询数据集
     * @param bo
     * @return
     */
    @SaIgnore
    @PostMapping("/hitsList")
    public TableDataInfo<DatasetsVo> hitsList(@RequestBody DatasetsBo bo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        bo.setDatasetStatus(2);
        bo.setListingStatus(1);
        return iDatasetsService.queryPageList(bo, pageQuery);
    }


    /**
     * 获取数据集主详细信息
     *
     * @param id 主键
     */
    @SaIgnore
    @PostMapping("/getDatasetsInfo")
    public R<DatasetsVo> getInfo(@RequestBody DatasetsBo bo) {
        return R.ok(iDatasetsService.queryDetailsById(bo.getId()));
    }

    /**
     * 获取数据集主详细信息
     *
     * @param id 主键
     */
    @PostMapping("/downFile")
    public R<List<DatasetFilesVo>> downFile(@RequestBody DatasetsBo bo) {
        //
        DatasetsVo datasetsVo = iDatasetsService.queryDetailsById(bo.getId());
        ServiceUsersVo serviceUsersVo = serviceUsersService.queryById(LoginHelper.getUserId());
        if(serviceUsersVo == null){
            return R.fail("用户不存在");
        }
        if(serviceUsersVo.getMemberType() == null || "ordinary".equals(serviceUsersVo.getMemberType()) || serviceUsersVo.getMemberEndTime().before(new Date())){
//            return R.fail("用户不是会员");

            UserPointsVo userPointsVo = userPointsService.queryById(LoginHelper.getUserId());
            if(userPointsVo == null){
                return R.fail("对不起，用户积分不足");
            }
            if(userPointsVo.getTotalPoints() < datasetsVo.getDowPointValue()){
                return R.fail("对不起，您的用户积分不足");
            }
            UserPointsBo userPointsBo = new UserPointsBo();
            userPointsBo.setUserId(LoginHelper.getUserId());
            userPointsBo.setTotalPoints(userPointsVo.getTotalPoints() - datasetsVo.getDowPointValue());
            userPointsService.updateByBo(userPointsBo);

            UserPointsVo pointsVo = userPointsService.queryById(datasetsVo.getCreateUserId());
            userPointsBo = new UserPointsBo();
            userPointsBo.setUserId(datasetsVo.getCreateUserId());
            userPointsBo.setCumulativePoints(pointsVo.getCumulativePoints() + datasetsVo.getDowPointValue());
            userPointsBo.setTotalPoints(pointsVo.getTotalPoints() + datasetsVo.getDowPointValue());
            userPointsService.updateByBo(userPointsBo);

            // 新增下载记录
            PointTransactionsBo transactionsBo = new PointTransactionsBo();
            transactionsBo.setDatasetId(bo.getId());
            transactionsBo.setDatasetName(datasetsVo.getTitle());
            transactionsBo.setUserId(LoginHelper.getUserId());
            transactionsBo.setPoints(Long.parseLong(datasetsVo.getDowPointValue().toString()));
            transactionsBo.setTransactionType("decrement");
            transactionsBo.setRemarks(datasetsVo.getCategoryName()+"");
            transactionsBo.setCreateUserId(datasetsVo.getCreateUserId());
            transactionsBo.setCreateUserName(LoginHelper.getUsername());
            transactionsBo.setImageUrl(datasetsVo.getCoverImagePath());
            transactionsBo.setCategoryId(Long.parseLong(datasetsVo.getCategoryId()));
            pointTransactionsService.insertByBo(transactionsBo);
//
//            pointsVo = userPointsService.queryById(LoginHelper.getUserId());
//            userPointsBo = new UserPointsBo();
//            userPointsBo.setUserId(LoginHelper.getUserId());
//            userPointsBo.setTotalPoints(pointsVo.getTotalPoints() - datasetsVo.getDowPointValue());
//            userPointsService.updateByBo(userPointsBo);
            bo.setDownloadValue(datasetsVo.getDownloadValue()+ 1);
            iDatasetsService.updateDowByBo( bo);

        }else {
            UserPointsVo pointsVo = userPointsService.queryById(datasetsVo.getCreateUserId());
            UserPointsBo userPointsBo = new UserPointsBo();
            userPointsBo.setCumulativePoints(pointsVo.getCumulativePoints() + datasetsVo.getDowPointValue());
            userPointsBo.setTotalPoints(pointsVo.getTotalPoints() + datasetsVo.getDownloadValue());
            userPointsService.updateByBo(userPointsBo);


            // 新增下载记录
            PointTransactionsBo transactionsBo = new PointTransactionsBo();
            transactionsBo.setDatasetId(bo.getId());
            transactionsBo.setDatasetName(datasetsVo.getTitle());
            transactionsBo.setUserId(LoginHelper.getUserId());
            transactionsBo.setPoints(Long.parseLong(datasetsVo.getDowPointValue().toString()));
            transactionsBo.setTransactionType("decrement");
            transactionsBo.setRemarks(datasetsVo.getCategoryName()+"");
            transactionsBo.setCreateUserId(datasetsVo.getCreateUserId());
            transactionsBo.setCreateUserName(LoginHelper.getUsername());
            transactionsBo.setImageUrl(datasetsVo.getCoverImagePath());
            transactionsBo.setCategoryId(Long.parseLong(datasetsVo.getCategoryId()));
            pointTransactionsService.insertByBo(transactionsBo);
            bo.setDownloadValue(datasetsVo.getDownloadValue()+ 1);
            iDatasetsService.updateDowByBo(bo);
        }
        return R.ok(datasetsVo.getFilesBos());
    }

    /**
     * 新增数据集主
     */
    @RepeatSubmit()
    @PostMapping("/add")
    public R<Void> add(@RequestBody DatasetsBo bo) {

        return toAjax(iDatasetsService.insertByBo(bo));
    }



    /**
     * 修改数据集主
     */
    @SaCheckPermission("service:datasets:edit")
    @Log(title = "数据集主", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DatasetsBo bo) {
        return toAjax(iDatasetsService.updateByBo(bo));
    }


    /**
     * 修改数据集主
     */
    @PostMapping("/editInfo")
    public R<Void> editInfo(@Validated(EditGroup.class) @RequestBody DatasetsBo bo) {
        return toAjax(iDatasetsService.updateDatasetsByBo(bo));
    }

    /**
     * 删除数据集主
     *
     * @param ids 主键串
     */
    @SaCheckPermission("service:datasets:remove")
    @Log(title = "数据集主", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iDatasetsService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


    /**
     * 查询数据集主列表
     */
    @SaIgnore
    @PostMapping("/myList")
    public TableDataInfo<DatasetsVo> myList(@RequestBody DatasetsBo bo) {

        if(bo.getSelTypeId() == 1){
            PageQuery pageQuery = new PageQuery();
            pageQuery.setPageNum(bo.getPageNum());
            pageQuery.setPageSize(bo.getPageSize());
            bo.setCreateUserId(getUserId());
            return iDatasetsService.queryPageList(bo, pageQuery);
        }else {
            //已下载
            PointTransactionsBo transactionsBo = new PointTransactionsBo();
            transactionsBo.setUserId(getUserId());
            List<PointTransactionsVo> list = pointTransactionsService.queryList(transactionsBo);
            List<String> ids = list.stream().map(PointTransactionsVo::getDatasetId).collect(Collectors.toList());
            bo.setIds(ids);
            PageQuery pageQuery = new PageQuery();
            pageQuery.setPageNum(bo.getPageNum());
            pageQuery.setPageSize(bo.getPageSize());
            return iDatasetsService.queryPageList(bo, pageQuery);
        }

    }
}
